using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace QiHe.ReliableData
{
    public class TypeHelper
    {
        public static List<Type> AtomTypes = new List<Type>();
        static TypeHelper()
        {
            AtomTypes.Add(typeof(bool));
            AtomTypes.Add(typeof(int));
            AtomTypes.Add(typeof(float));
            AtomTypes.Add(typeof(double));
            AtomTypes.Add(typeof(string));
        }

        public static bool IsAtomType(Type type)
        {
            return AtomTypes.Contains(type) || type.IsEnum;
        }

        public static bool IsGenericList(Type type)
        {
            Type ilist = type.GetInterface("IList");
            return ilist != null && type.IsGenericType;
        }

        public static Type MakeListType(Type itemType)
        {
            return typeof(List<>).MakeGenericType(itemType);
        }

        public static string MakeListType(string typeName)
        {
            return String.Format("List<{0}>", typeName);
        }

        public static bool IsListType(string typeName)
        {
            return typeName.StartsWith("List<");
        }

        public static string GetItemType(string listTypeName)
        {
            return listTypeName.Substring(5).TrimEnd('>');
        }

        public static string TryGetName(object data)
        {
            Type type = data.GetType();
            PropertyInfo pi = type.GetProperty("Name", typeof(string));
            string name = null;
            if (pi != null)
            {
                name = (string)pi.GetValue(data, null);
            }
            if (name != null) return name;
            else return type.Name;
        }

        public static string TryGetName(object data, string name)
        {
            Type type = data.GetType();
            PropertyInfo pi = type.GetProperty("Name", typeof(string));
            if (pi != null)
            {
                return (string)pi.GetValue(data, null);
            }
            return name;
        }

    }
}
